package com.romeo_foxtrot.labs.vaadin;

import java.io.Serializable;

import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HandlerRegistration;

public class EventBus implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1102563425505641311L;

	private final HandlerManager handlerManager;

	public EventBus() {
		handlerManager = new HandlerManager(null);
	}

	public EventBus(Object source) {
		handlerManager = new HandlerManager(source);
	}

	/**
	 * re-entry is allowed and will have not effect
	 * 
	 * @param <H>
	 * @param type
	 * @param handler
	 * @return null on re-entry with the same parameters
	 */
	public <H extends EventHandler> HandlerRegistration addHandler(
			GwtEvent.Type<H> type, final H handler) {

		HandlerRegistration registration;

		/*
		 * prevents double
		 */
		boolean registered = false;
		int count = handlerManager.getHandlerCount(type);
		for (int i = 0; i < count; i++) {
			if (handler == handlerManager.getHandler(type, i)) {
				registered = true;
				break;
			}
		}

		if (registered) {
			registration = null;
		} else {
			registration = handlerManager.addHandler(type, handler);
		}

		return registration;
	}

	public void fireEvent(GwtEvent<?> event) {
		handlerManager.fireEvent(event);
	}
}
